#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash libint-2.6.0.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

get_libint_integrate()
{
cnt=1
number=10
while [ $cnt -lt $number ]
do
    set +e
    echo "正在下载libint源码包，时间较长，请耐心等待......"
    wget -t 1 -c -P $buildpath https://github.com/cp2k/libint-cp2k/releases/download/v2.6.0/libint-v2.6.0-cp2k-lmax-6.tgz
    result_code=$?
    if [ $result_code -ne 0 ];then
        cnt=$[$cnt+1]
    else
        echo "下载libint源码包成功"
        tar -xvf $buildpath/libint-v2.6.0-cp2k-lmax-6.tgz -C $buildpath && rm -rf $buildpath/libint-v2.6.0-cp2k-lmax-6.tgz
        break
    fi   
done

if [ $cnt -eq $number ];then
    echo "下载libint源码包失败,将dependency/src目录下的离线包拷贝并解压到构建目录下"
    cp dependency/src/libint-v2.6.0-cp2k-lmax-6.tgz $buildpath/libint-v2.6.0-cp2k-lmax-6.tgz
    tar -xvf $buildpath/libint-v2.6.0-cp2k-lmax-6.tgz -C $buildpath && rm -rf $buildpath/libint-v2.6.0-cp2k-lmax-6.tgz
fi
set -e 
}

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
set -e
yum install -y wget tar environment-modules

get_libint_integrate

cd $buildpath/libint-v2.6.0-cp2k-lmax-6
export LDFLAGS="-L$installpath/gmp-6.2.0/lib -L$installpath/boost-1.72.0/lib"
export CPPFLAGS="-I$installpath/gmp-6.2.0/include -I$installpath/boost-1.72.0/include/"
./configure --prefix=$installpath/libint-2.6.0 CC=mpicc CXX=mpicxx FC=mpifort --enable-fortran --enable-shared
make -j$(nproc) && make install
cat>"$installpath/libint-2.6.0/libint_modulefiles"<<EOF
#%Module1.0
conflict libint
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set LIBINT \$pwd
setenv LIBINT \$LIBINT
prepend-path LD_LIBRARY_PATH \$LIBINT/lib
prepend-path INCLUDE \$LIBINT/include
EOF

rm -rf $buildpath/libint-v2.6.0-cp2k-lmax-6
